package com.pig4cloud.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.mall.product.entity.Brand;
import com.pig4cloud.mall.product.entity.Category;
import com.pig4cloud.mall.product.entity.CategoryBrandRelation;
import com.pig4cloud.mall.product.mapper.BrandMapper;
import com.pig4cloud.mall.product.mapper.CategoryBrandRelationMapper;
import com.pig4cloud.mall.product.mapper.CategoryMapper;
import com.pig4cloud.mall.product.service.CategoryBrandRelationService;
import com.pig4cloud.pig.common.core.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 品牌分类关联
 *
 * @author fangyu
 * @date 2020-11-25 14:58:43
 */
@Service
public class CategoryBrandRelationServiceImpl extends ServiceImpl<CategoryBrandRelationMapper, CategoryBrandRelation> implements CategoryBrandRelationService {

	@Autowired
	private BrandMapper brandMapper;
	@Autowired
	private CategoryMapper categoryMapper;

	@Override
	public R saveDetail(CategoryBrandRelation categoryBrandRelation) {
		long brandId = categoryBrandRelation.getBrandId();
		long categoryId = categoryBrandRelation.getCatelogId();
		int count = baseMapper.selectCount(new QueryWrapper<CategoryBrandRelation>().eq("brand_id", brandId).eq("catelog_id", categoryId));
		// 如果存在则不能插入
		if (count > 0) {
			return R.failed("当前关联关系已存在!");
		}
		// 1、查询详细名字
		Brand brand = brandMapper.selectById(brandId);
		Category category = categoryMapper.selectById(categoryId);
		categoryBrandRelation.setBrandName(brand.getName());
		categoryBrandRelation.setCatelogName(category.getName());
		int i = baseMapper.insert(categoryBrandRelation);
		System.out.println(i);
		if (i > 0) {
			return R.ok("添加成功!");
		} else {
			return R.failed("添加失败!");
		}
	}

	@Override
	public List<CategoryBrandRelation> getByBrandId(Long brandId) {
		return baseMapper.selectList(new QueryWrapper<CategoryBrandRelation>().eq("brand_id", brandId));
	}
}
